package juc;

import java.util.concurrent.*;

public class MyThreadPoolDemo {
	public static void main(String args[]) {
		// ExecutorService threadPool = Executors.newFixedThreadPool(5);
		// ExecutorService threadPool = Executors.newSingleThreadExecutor();
		// ExecutorService threadPool = Executors.newCachedThreadPool();
		ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 5, 3, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
		try {

			for (int i = 0; i < 10; i++) {
				int finalI = i;
				threadPool.execute(() -> {
					// System.out.println(Thread.currentThread().getName());
					if (finalI < 3) {
						System.out.println(finalI + ": " + threadPool.getActiveCount());
					} else if (finalI < 5) {
						System.out.println(finalI + ": " + threadPool.getActiveCount());
					} else if (finalI < 7) {
						System.out.println(finalI + ": " + threadPool.getActiveCount());
					} else {
						try {
							TimeUnit.SECONDS.sleep(2);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println(finalI + ": " + threadPool.getActiveCount());

					}
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			threadPool.shutdown();
		}
	}
}
